﻿// 请求转Json
function QueryStringToJson(querystring) 
{
    var json = {};

    if (!querystring) return json;

    querystring = querystring.match(/[^\?]+\=.*?[^\#]/);

    if (!querystring || !querystring[0]) return json;

    querystring = querystring[0];

    var items = querystring.match(/[^&]+\=[^&]*/g);

    for (var idx in items) {
        var item = items[idx].split('=');
        var key = item[0];
        var value = item[1];

        if (!json[key]) {
            json[key] = value;
            continue;
        }

        if (!(json[key] instanceof Array)) {
            json[key] = [json[key]];
        }

        json[key].push(value);
    }

    for (var idx in json) {
        if (json[idx] instanceof Array) {
            json[idx] = json[idx].join(',')
        }
    }

    return json;
}

function LoadingBox(selector) {
    this.Text = "Loading...";

    if (!selector) return null;

    var container = $(selector);
    var loadingbox = null;

    this.Show = function () {
        this.Hide();
        loadingbox = $('<div class="loading-message loading-message-boxed">' +
                       '<img src="/assets/global/img/loading-spinner-grey.gif" align="">' +
                       '<span>&nbsp;&nbsp;' + this.Text + '</span>' +
                       '</div>');

        container.append(loadingbox);

        loadingbox.css({
            left: (container.width() - loadingbox.width()) / 2,
            top: 50,
            position: "absolute"
        });
    }

    this.Hide = function () {
        if (loadingbox) loadingbox.remove();
    }
}

$.fn.extend({
    // Ajax表单
    AjaxForm: function (options) {
        var _opt = {
            submitButton: {
                selector: null, // 必填，按钮选择器
                icon: "fa fa-spinner fa-spin",  // 执行时显示图标，空字符串或null则不显示图标
                autoDisable: true, // 是否自动无效化提交按钮
                loadingText: "正在执行"    // 执行时显示文本
            },  // 提交按钮
            resetButton: {
                selector: null,  // 重置按钮（可以不填写）, selector
                reset: null     // 自定义重置方法 reset(jQueryForm)
            },
            alertTitle: null,
            validate: function (d) { return true; },
            //--------- Ajax 相关参数 ---------
            url: null,
            data: null,
            accepts: null,
            async: null,
            cache: null,
            complete: null,
            contentType: null,
            dataType: null,
            error: null,
            timeout: 10000,
            type: "POST",
            success: null,
            notCompletedResetForm: function () { }     // 完成后若成功，是否不要重置表单，若为false表示使用默认的方法来重置，否则按自定义方法重置 notCompletedResetForm(data)
        };
        // 表单对象
        var self = this;
        // ajax 参数
        var ajaxOptions = {};

        if (options) {
            // 合并提交按钮相关参数
            options.submitButton = $.extend(_opt.submitButton, options.submitButton);

            // 合并取消按钮相关参数
            options.resetButton = $.extend(_opt.resetButton, options.resetButton);

            $.extend(_opt, options);
        }

        if (!_opt.submitButton) {
            if (console) {
                console.error("submitButton参数未提供");
            } else {
                alert("submitButton参数未提供");
            }

            return this;
        }

        if (!_opt.submitButton.selector) {
            if (console) {
                console.error("submitButton选择器未提供");
            } else {
                alert("submitButton选择器未提供");
            }

            return this;
        }

        var btnSubmit = $(_opt.submitButton.selector);
        var btnReset = null;
        btnSubmit.defaultText = btnSubmit.text();

        ajaxOptions.url = _opt.url ? _opt.url : self.attr("action");
        if (_opt.accepts) ajaxOptions.accepts = _opt.accepts;
        if (_opt.async) ajaxOptions.async = _opt.async;
        if (_opt.cache) ajaxOptions.cache = _opt.cache;
        if (_opt.type) ajaxOptions.type = _opt.type;
        if (_opt.contentType) ajaxOptions.contentType = _opt.contentType;
        if (_opt.dataType) ajaxOptions.dataType = _opt.dataType;
        ajaxOptions.timeout = _opt.timeout;
        ajaxOptions.complete = function (xhr, textStatus) {
            if (typeof (_opt.complete) == "function")
                _opt.complete.call(this, xhr, textStatus);
            btnSubmit.html(btnSubmit.defaultText);
            if (_opt.submitButton.autoDisable)
                btnSubmit.removeAttr("disabled");
        };
        ajaxOptions.error = typeof (_opt.error) == "function" ? _opt.error : function (xhr, textStatus, errorThrown) {
            var msg = "程序遇到未知问题，运行被中断";
            if (_opt.alertTitle) {
                toastr["error"](msg, _opt.alertTitle);
            } else {
                toastr["error"](msg);
            }
        };
        ajaxOptions.success = typeof (_opt.success) == "function" ?
            function (data, textStatus, xhr) {
                _opt.success.call(this, data, _opt.alertTitle, textStatus, xhr);
                if (data.Result) {
                    if (_opt.notCompletedResetForm) {
                        _opt.notCompletedResetForm.call(this, ajaxOptions.data);
                    } else {
                        self.find("[name]")
                            .each(function () {
                                var element = $(this);
                                if ((this.type == "checkbox" || this.type == "radio") && this.checked) {
                                    element.trigger("click");
                                    this.defaultChecked = false;
                                }
                                if (this.tagName == "SELECT") {
                                    element.children("option").each(function () {
                                        this.defaultSelected = false;
                                        this.selected = false;
                                    });
                                }
                                for (var i in ajaxOptions.data) {
                                    if (this.name != ajaxOptions.data[i]["name"]) continue;

                                    if ((this.type == "checkbox" || this.type == "radio") && this.value == ajaxOptions.data[i]["value"]) {
                                        element.trigger("click");
                                        this.defaultChecked = true;
                                        continue
                                    }

                                    if (this.tagName == "SELECT") {
                                        element.children("option").each(function () {
                                            if (this.value != ajaxOptions.data[i]["value"]) return;
                                            this.defaultSelected = true;
                                            this.selected = true;
                                        });
                                        continue;
                                    }

                                    this.defaultValue = ajaxOptions.data[i]["value"];
                                }
                            });
                    }

                    resetForm();
                }
            } :
            function (data, textStatus, xhr) {
                var args = [data.Message];

                if (_opt.alertTitle) args.push(_opt.alertTitle);

                if (data.Result) {
                    toastr["success"].apply(this, args);
                    resetForm();
                } else {
                    toastr["error"].apply(this, args);
                }
            };

        self.bind("submit", function () {
            return false;
        });

        // 绑定提交按钮
        btnSubmit.bind("click", function () {
            var msg = "表单验证未通过，请核对后再次尝试一下！";
            if (self.valid && !self.valid()) {
                if (_opt.alertTitle) {
                    toastr["warning"](msg, _opt.alertTitle);
                } else {
                    toastr["warning"](msg);
                }
                return false;
            }

            if (_opt.data) {
                if (typeof (_opt.data) == "function") {
                    ajaxOptions.data = _opt.data.call(self);
                } else {
                    ajaxOptions.data = _opt.data;
                }
            } else {
                ajaxOptions.data = self.serializeArray();
            }
            if (ajaxOptions.url.indexOf('ajax=true') == -1) {
                var hasValue = false;
                for (var i = 0; i < ajaxOptions.data.length; i++) {
                    if (ajaxOptions.data[i]["name"] == 'ajax') {
                        hasValue = true;
                        break;
                    }
                }
                if (!hasValue) {
                    ajaxOptions.data.push({ "name": "ajax", "value": true });
                }
            }

            if (!_opt.validate.call(this, ajaxOptions.data, _opt.alertTitle)) {
                return false;
            }

            var html = "";
            if (_opt.submitButton.icon)
                html += '<i class="' + _opt.submitButton.icon + '"></i> ';
            html += _opt.submitButton.loadingText;
            btnSubmit.empty().append(html);
            if (_opt.submitButton.autoDisable)
                btnSubmit.attr("disabled", "disabled");

            $.ajax(ajaxOptions);
        });

        if (_opt.resetButton.selector) {
            btnReset = $(_opt.resetButton.selector);
            if (typeof (_opt.resetButton.reset) == "function") {
                btnReset.bind("click", function () {
                    _opt.resetButton.reset.call(self);
                });
            } else {
                btnReset.bind("click", function () {
                    self.trigger("reset");
                });
            }
        }

        function resetForm() {
            if (btnReset) {
                btnReset.trigger("click");
            } else {
                if (typeof (_opt.resetButton.reset) == "function") {
                    _opt.resetButton.reset.call(self);
                } else {
                    self.trigger("reset");
                }
            }
        }

        return this;
    }
});

/*
 * Post提交数据生成类
 */
function PostData() {
    var _postData = [];

    this.Add = function (key, value) {
        _postData.push({ "name": key, "value": value });
    }

    this.GetData = function () {
        return _postData;
    }
}

/*
 * 将字符串转换为日期型
 */
function CDate(str, format) {
    var F = (format || "yyyy-mm-dd hh:ii").split(/[^\w]+/);
    var D = str.split(/[^\d]+/);
    var y, m, d, h, i;

    if (F.length != D.length) {
        console.warn("日期格式不正确");
        return;
    }

    for (var i in F) {
        switch (F[i][0]) {
            case "y":
                y = D[i];
                break;
            case "m":
                m = parseInt(D[i]) - 1;
                break;
            case "d":
                d = D[i];
                break;
            case "h":
                h = D[i];
                break;
            case "i":
                i = D[i];
                break;
        }
    }

    return new Date(y, m, d, h, i);
}